package com.xinxi.floatingdemo;

import android.content.Context;
import android.support.design.widget.FloatingActionButton;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;

/**
 * Created by Administrator on 2018/5/11.
 */

public class MoveView extends View {
    private static final String TAG = "moveView";

    public MoveView(Context context) {
        super(context);
    }

    public MoveView(Context context, AttributeSet attrs) {
        super(context, attrs);

    }

    public MoveView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

    }

    int lastX;
    int lastY;

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int rawX = (int) event.getRawX();
        int rawY = (int) event.getRawY();
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                lastX = (int) event.getRawX();
                lastY = (int) event.getRawY();
                break;

            case MotionEvent.ACTION_MOVE:
                int dx = rawX - lastX;
                int dy = rawY - lastY;

                //方法1
                setX(getX()+dx);
                setY(getY()+dy);

                //方法2
                offsetLeftAndRight(dx);
                offsetTopAndBottom(dy);

                //方法3
                layout((int) getX() + dx, (int) getY() + dy, (int) getX() + dx + getWidth(), (int) getY() + dy + getHeight());

                Log.i(TAG, "onTouchEvent: " + getLeft() + "     " + getX() + "           " + getTranslationX());
                lastX = rawX;
                lastY = rawY;
                break;
        }
        return super.onTouchEvent(event);
    }

}
